import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:gameplay_flutter/lib_baseview/lib_baseview.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:ones/ui.dart';

import '../../../generated/assets.dart';
import '../../../lib_runtime/common/lanuage_util.dart';
import '../../../resource/language/generated/l10n.dart';
import 'fresh_components.dart';

class PopularTabsWidget extends StatefulWidget {
  final callback;
  final controller;
  const PopularTabsWidget({super.key, required this.callback, required this.controller,});


  @override
  State<PopularTabsWidget> createState() => _PopularTabsWidget();
}

class _PopularTabsWidget extends State<PopularTabsWidget> with SingleTickerProviderStateMixin {
  final EasyRefreshController _refreshControllerRoom = EasyRefreshController ();
  late TabController _tabController;
  bool hasMore = false;
  int queryType = 0;
  bool noMore = false;
  int pageNum = 1;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: widget.controller.roomTagsList.value.length,
      vsync: this,
    );
    _tabController.addListener((){
      setState(() {
        queryType = _tabController.index;
      });
      widget.controller.loadPopularData(widget.controller.roomTagsList.value[_tabController.index].roomCategoryIds,'refresh',1);
    });
  }

  Future<void> _onRefreshPopularRoom()async {
    // _refreshControllerMarket.finishRefresh(success: true);
    widget.controller.loadPopularData(widget.controller.roomTagsList.value[queryType].roomCategoryIds,'refresh',1);
    _refreshControllerRoom.finishLoad(noMore: false);
    setState(() {
      noMore = false;
      pageNum = 1;
    });
  }

  Future<void> _onLoadRoom() async {
    if(widget.controller.popularList.value.isEmpty){
      setState(() {
        noMore = true;
      });
    }else {
      if(!noMore){
        setState(() {
          pageNum++;
          hasMore = true;
        });
        var status =  await widget.controller.loadPopularData(widget.controller.roomTagsList.value[queryType].roomCategoryIds,'more', pageNum++);
        if(!status){
          _refreshControllerRoom.finishLoad(noMore: true);
        }
      } else {
        setState(() {
          noMore = false;
        });
        Future.delayed(Duration(milliseconds: 1000), () {
          setState(() {
            noMore = true;
          });
        });
      }
    }
    // _refreshControllerMarket.finishRefresh(success: true);
  }


  Widget _popularList(controller){
   return EasyRefresh(
        onRefresh: _onRefreshPopularRoom,
        onLoad:_onLoadRoom,
        header: buildCustomHeader,
        footer:buildCustomFooter,
        controller: _refreshControllerRoom,
        child:controller.popularList.value.isNotEmpty? MasonryGridView.count(
          crossAxisCount: 1,
          mainAxisSpacing: 6,
          crossAxisSpacing: 4,
          itemCount: controller.popularList.length,
          itemBuilder: (context, index) {
            var newColors = 0;
            var newBgColors = 0;
            var roomItem;
            try{
              roomItem  =  controller.popularList.value[index];
              if(roomItem.roomCategoryColor != null){
                String color = '0xff' + roomItem.roomCategoryColor.split('#')[1];
                newColors = color.toInt();
              } else {
                newColors = 0xffc1c1c1;
              }
              if(roomItem.backgroundUrl != null){
                String bgColor = '0xff' + roomItem.backgroundUrl.split('#')[1];
                newBgColors = bgColor.toInt();
              } else {
                newBgColors = 0xffc1c1c1;
              }
            }catch(e){
              return Container();
            }
            return Container(
                decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(5))
                ),
                padding: const EdgeInsets.symmetric(vertical: 5),
                child: Column(
                  children: [
                    Row(
                      children: [
                        // Image.asset(roomItem.roomIcon,width: 100,height: 100,),
                        Container(
                            width: 73,
                            height: 73,
                            margin: const EdgeInsets.only(left: 5),
                            decoration: ShapeDecoration(
                                image:DecorationImage(
                                  // image:index % 2 == 0 ? AssetImage(Assets.homeAvatar1) : AssetImage(Assets.homeAvatar2),
                                    image: NetworkImage(roomItem.roomIcon?? ''),
                                    fit: BoxFit.fitWidth
                                ),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadiusDirectional.circular(8))
                            ),
                            child: Stack(
                              children: [
                                controller.popularTopList.value.any((item)=> item.roomNo == roomItem.roomNo)?Positioned(
                                  child: Container(
                                    width: 40.w,
                                    height: 16.h,
                                    padding: const EdgeInsets.only(bottom: 2),
                                    decoration: BoxDecoration(
                                        color:controller.popularTopList.value[0].roomNo == roomItem.roomNo? Color(0xffFFC046):(controller.popularTopList.value[1].roomNo == roomItem.roomNo? Color(0xffFCE730):Color(0xff6AA1F2)),
                                        borderRadius: const BorderRadius.only(topLeft: Radius.circular(8),bottomRight: Radius.circular(8))
                                    ),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      crossAxisAlignment: CrossAxisAlignment.end,
                                      children: [
                                        Container(
                                          height: 4,
                                          width: 2,
                                          margin:const EdgeInsets.only(bottom: 3),
                                          decoration:const BoxDecoration(
                                              color: Colors.white
                                          ),
                                        ),
                                        const SizedBox(width: 1,),
                                        Container(
                                          height: 8,
                                          width: 2,
                                          margin:const EdgeInsets.only(bottom: 3),
                                          decoration:const BoxDecoration(
                                              color: Colors.white
                                          ),
                                        ),
                                        const SizedBox(width: 1,),
                                        Container(
                                          height: 5,
                                          width: 2,
                                          margin: const EdgeInsets.only(bottom: 3),
                                          decoration:const BoxDecoration(
                                              color: Colors.white
                                          ),
                                        ),
                                        const SizedBox(width: 2,),
                                        Text('top').color(Colors.white).fontSize(10),
                                        Text(controller.popularTopList.value[0].roomNo == roomItem.roomNo?'1':(controller.popularTopList.value[1].roomNo == roomItem.roomNo?'2':"3")).color(Colors.white).fontSize(12)
                                      ],
                                    ),
                                  ),
                                ):Container(),
                              ],
                            )
                        ),
                        const SizedBox(width: 5,),
                        Expanded(child: SizedBox(
                          height:73,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      roomItem.countryUrl != null?Image.network(roomItem.countryUrl,width: 30,height: 20,):const Image(image:AssetImage(Assets.homeCountries),width: 30,height: 20,),
                                      const SizedBox(width: 3,),
                                      SizedBox(
                                        width: 180,
                                        child: Text(
                                          roomItem.roomName,
                                          softWrap: false,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        ).fontSize(16),
                                      )
                                    ],
                                  ),
                                  Text(
                                    roomItem.slogan ?? '',
                                    softWrap: false,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ).fontSize(12).color(const Color(0xffC1C1C1)),
                                ],
                              ),
                              Row(
                                children: [
                                  roomItem.categoryTypeIcon != null?Image.network(roomItem.categoryTypeIcon,width: 24,):const Image(image:AssetImage(Assets.homeIcRoomLove),width: 24,),
                                  const SizedBox(width: 4,),
                                  Container(
                                    padding: const EdgeInsets.fromLTRB(8, 1, 8, 1),
                                    decoration: BoxDecoration(
                                        borderRadius: const BorderRadius.all(Radius.circular(10)),
                                        color: Color(newBgColors)
                                    ),
                                    child: Text(roomItem.roomCategoryName).fontSize(10).colorInt(newColors),
                                  ),
                                  const Spacer(),
                                  const Image(image: AssetImage(Assets.homeIcFire,),width: 12,height: 12,),
                                  const SizedBox(width: 5,),
                                  Text(roomItem.scoreWeight.toString()).fontSize(12).colorInt(0xffC1C1C1),
                                ],
                              ),
                            ],
                          ),
                        ).marginLeft(10).paddingRight(8.0),)
                      ],
                    ).roundedRect(8).paddingAll(5).colorBg(bgColor: Colors.white).onClick(() {
                      controller.joinRoomPage(context,roomItem);
                    }),
                  ],
                )
            );

          },
        ) : Center(
          child: Image.asset(Assets.noData,fit: BoxFit.fill,),
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: DefaultTabController(
        length: widget.controller.roomTagsList.value.length,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SafeArea(child:
              SizedBox(
                width: MediaQuery.sizeOf(context).width,
                child: TabBar(
                  controller: _tabController,
                  splashFactory: NoSplash.splashFactory,
                  labelPadding: EdgeInsets.symmetric(horizontal: 12.0),
                  // unselectedLabelColor:Color(0xffc1c1c1),
                  // labelColor: Color(0xff8A72FE),
                  // indicatorPadding: EdgeInsets.symmetric(vertical: 10,),
                  // indicatorSize: TabBarIndicatorSize.tab,
                  tabAlignment: TabAlignment.start,
                  isScrollable: true,
                  dividerHeight: 0,
                  indicatorColor: const Color(0xfffafafa),
                  // indicator:BoxDecoration(
                  //     border: Border.all(color:  Color(0xff8A72FE),width: 1),
                  //     borderRadius:BorderRadius.circular(50),
                  //     color: Colors.transparent
                  // ),
                  tabs: List.generate(widget.controller.roomTagsList.value.length, (index) =>
                      Tab(
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8,vertical: 3),
                          decoration: BoxDecoration(
                            color: queryType == index?const Color(0xffffffff) : const Color(0xfff4f4f4),
                            borderRadius: const BorderRadius.all(Radius.circular(18)),
                            border: queryType == index?Border.all(color: const Color(0xff8A72FE ),width: 1):null
                          ),
                          child: Text(widget.controller.roomTagsList.value[index].roomCategoryName,
                            style: TextStyle(
                              color: queryType == index ? const Color(0xff8A72FE) : const Color(0xffC1C1C1)
                            ),
                          ),
                        ),
                      )
                  ),
                ),
              )
            ),
           Expanded(
               child:  Listener(
                 onPointerMove: (PointerMoveEvent event) {
                   double deltaX = event.delta.dx;
                   double dy = event.delta.dy;
                   if(dy < 10 && dy > -10 && deltaX > 15){
                     print(_tabController.index);
                     if(_tabController.index == 0 && !LanguageUtil().isRTL()){
                       widget.callback('left');
                     }  else if(_tabController.index == widget.controller.roomTagsList.value.length - 1 && LanguageUtil().isRTL()){
                       widget.callback('right');
                     }
                   }
                   if(dy < 10 && dy > -10 && deltaX < -15){
                     if(_tabController.index == widget.controller.roomTagsList.value.length - 1&& !LanguageUtil().isRTL()){
                       widget.callback('right');
                     }  else if(_tabController.index == 0 && LanguageUtil().isRTL()){
                       widget.callback('left');
                     }
                   }
                 },
                 child:TabBarView(
                   controller: _tabController,
                   children: List.generate(widget.controller.roomTagsList.value.length, (index) =>
                       _popularList(widget.controller)
                   ),
                 ),
               ),
           ),
            SizedBox(height: 50,)
          ],
        ),
      ),
    );
  }


}
